package com.comment.service.impl;

import com.comment.dto.Result;
import com.comment.entity.SeckillVoucher;
import com.comment.entity.VoucherOrder;
import com.comment.mapper.VoucherOrderMapper;
import com.comment.service.ISeckillVoucherService;
import com.comment.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comment.utils.RedisIdWorker;
import com.comment.utils.SimpleRedisLock;
import com.comment.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * lua脚本
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 阻塞队列
     */
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);

    /**
     * 线程池
     */
    private ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VocherOrderHandler());
    }
    private class VocherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.创建订单
                } catch (InterruptedException e) {
                    log.error("处理订单异常",e);
                }

            }
        }
    }

    private void handleVoucherlOrder(VoucherOrder voucherOrder) {
        // 1.获取用户
        Long userId = voucherOrder.getUserId();

    }
    /*
    * 代理对象
    */
    private IVoucherOrderService proxy;
    /**
     * 优惠券秒杀下单
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1.执行lua脚本（判断是否可以购买 0具备 1库存不足 2不能重复下单）
        Long flag = stringRedisTemplate.execute(
                SECKILL_SCRIPT, // 脚本
                Collections.emptyList(), // 脚本的参数
                voucherId.toString(), // 优惠券id
                UserHolder.getUser().getId().toString());// 用户id
        // 2.判断结果是否具备购买资格（0具备 1库存不足 2不能重复下单）
        int i = flag.intValue();
        if (i != 0){
            // 2.1.不为0，不具备购买资格，返回错误信息
            return Result.fail(flag == 1 ? "库存不足" : "不能重复下单");
        }
        // 2.2.为0，具备购买资格
        // 3.保存订单信息到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);

        orderTasks.add(voucherOrder);

        // 4.获取代理对象
        IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 5..返回订单id
        return Result.ok(orderId);
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 5.一人一单
        // 5.1查询订单信息
        Long userId = UserHolder.getUser().getId();

        int count = query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();
        // 5.2判断是否使用过优惠券
        if (count > 0) {
            return Result.fail("该用户已经使用过一张优惠券");
        }

        // 6.扣减库存-1
        boolean flag = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherId) // where id = #{voucherId}
                // .eq("stock",voucher.getStock()) // where stock = #{voucher.getStock()}
                .gt("stock", 0) // where stock > 0
                .update();
        if (!flag) {
            return Result.fail("优惠券库存不足");
        }

        // 7.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 7.1.订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 7.2.用户id
        voucherOrder.setUserId(userId);
        // 7.3.代金券id
        voucherOrder.setVoucherId(voucherId);
        // 7.4.保存订单
        save(voucherOrder);
        // 7.返回订单id
        return Result.ok(orderId);
    }
}
